package com.elh.stack;


import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;

/**
 * @author liulei
 **/
@Slf4j
public class MyStack<T> {

    private Object[] data;

    private int size;

    private int top;

    public MyStack() {
        this(5);
    }

    public MyStack(int initialCapacity) {
        if (initialCapacity <= 0) {
            throw new IllegalArgumentException("栈初始容量不能小于等于0: " + initialCapacity);
        }
        this.size = initialCapacity;
        this.top = -1;
        this.data = new Object[size];
    }

    /**
     * 入栈
     *
     * @param t
     */
    public void push(T t) {
        growUp();
        data[++top] = t;
    }

    /**
     * 数据扩容
     *
     */
    private void growUp() {
        if(this.top  >= (size - 1)){
            int newCapacity = size << 1; // 左移一位，相当于*2
            // 不超过int最大值
            newCapacity = newCapacity - Integer.MAX_VALUE > 0 ? Integer.MAX_VALUE : newCapacity;
            data = Arrays.copyOf(data,newCapacity);
            size = newCapacity;
        }
    }

    /**
     * 出栈
     *
     * @return
     */
    public T pop() {
        if (!isEmpty()) {
            return (T) data[top--];
        }
        return null;
    }


    /**
     * 访问栈顶数据
     *
     * @return
     */
    public T peek() {
        return (T)data[top];
    }

    /**
     * 栈是否满了
     *
     * @return
     */
    public boolean isFull() {
        return size == (top + 1);
    }

    /**
     * 栈是否为空
     *
     * @return
     */
    public boolean isEmpty() {
        return top == -1;
    }
}
